//
//  TestListIndexViewController.m
//  MKUITestApp
//
//  Created by 苏尚进 on 2025/11/26.
//  Copyright © 2025 moon. All rights reserved.
//

#import "TestListIndexViewController.h"
#import "TestElementHeaders.h"
#import "TestFunButton.h"
@interface TestListIndex_HeadView()
@end
@implementation TestListIndex_HeadView
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.backgroundColor = self.bgColor;
    }
    return self;
}
- (UIColor *)bgColor{
    return UIColor.blueColor;
}
- (CGSize)sizeThatFits:(CGSize)size{
    return CGSizeMake(size.width, 44);
}
- (void)setScrollView:(UIScrollView *)scrollView{
    if(_scrollView==scrollView)return;
    if(_scrollView){
        [_scrollView mk_removeObserverForKeyPath:NSStringFromSelector(@selector(contentOffset))];
    }
    _scrollView = scrollView;
    if(_scrollView){
        @MK_WEAKIFY(self);
        [_scrollView mk_addObserverForKeyPath:NSStringFromSelector(@selector(contentOffset)) options:(NSKeyValueObservingOptionNew) context:nil block:^(NSString * _Nonnull keyPath, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change, void * _Nonnull context) {
            @MK_NORMALIZE(self);
            [self _onScroll];
        }];
        [self _onScroll];
    }else{
        self.backgroundColor = self.bgColor;
    }
}
- (void)_onScroll{
    CGFloat y0 = self.scrollView.mk_contentOffsetOfMinY;
    CGFloat y1 = self.scrollView.contentOffset.y;
//    NSLog(@"y1:%@",@(y1));
    CGFloat progress = (y1-y0)/44.0;
    progress = MAX(0,progress);
    progress = MIN(1,progress);
    UIColor *c0 = [self.bgColor mk_colorWithAlpha:1];
    UIColor *c1 = [self.bgColor mk_colorWithAlpha:0.5];
    self.backgroundColor = MKUIColorInterpolate(c0, c1, progress);
}
@end

@interface TestListIndex_TabCell()
@end
@implementation TestListIndex_TabCell
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.tabController = [[MKUITabBarController alloc] initWithItemContainerClass:MKUITabBarItemFlowContainer.class contentContainerClass:MKUITabBarContentContainerOneTabView.class];
        self.tabController.delegate = self;
        self.barContainer = self.tabController.itemContainer;
        self.contentContainer = self.tabController.contentContainer;
        [self.contentView addSubview:self.contentContainer];
        [self.contentView addSubview:self.barContainer];
        //
        self.flowlayout = [[MKUIFlowLayoutConstraint alloc] initWithItems:@[self.barContainer,self.contentContainer] constraintParam:(MKUIFlowLayoutConstraintParam_V_C_C) contentInsets:UIEdgeInsetsZero interitemSpacing:0];
        [self reloadData];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.contentView.bounds;
    self.flowlayout.bounds = bounds;
    [self.flowlayout layoutItemsWithResizeItems:YES];
}
- (CGSize)sizeThatFits:(CGSize)size{
    return [self.flowlayout sizeThatFits:CGSizeMake(size.width, 9999) resizeItems:YES];
}
- (void)reloadData{
    NSMutableArray *contents = [[NSMutableArray alloc] init];
    for(int i=0;i<3;i++){
        TestListIndex_TabList1 *tabContent = [[TestListIndex_TabList1 alloc] initWithName:[NSString stringWithFormat:@"TabList_%@",@(i+1)]];
        [contents addObject:tabContent];
    }
    self.tabController.contents = contents;
    self.tabController.selectedIndex = 0;
    [self.tabController reloadData];
}

- (CGFloat)topMargginOfPinning{
    return 0;
}
- (void)listViewDidChangeContentOffset:(MKUIListView *)listView{
    [self _updateDisplayCells:listView];
    [self _updatePin:listView];
}
- (void)_updateDisplayCells:(MKUIListView *)listView{
    TestListIndex_TabListBase *tabContent = (TestListIndex_TabListBase *)self.tabController.selectedContent;
    [tabContent notifyOutListViewScroll:listView];
}
- (void)_updatePin:(MKUIListView *)listView{
    //
    MKUITabBarItemFlowContainer *barContainer = self.barContainer;
    UIView *pinView = barContainer;
    CGRect f1 = [pinView.superview convertRect:barContainer.mk_frameSafety toView:listView];
    //调整transform
    CGPoint offset = listView.contentOffset;
    UIEdgeInsets contentInsets = listView.mk_adjustedContentInset;
    CGAffineTransform m = CGAffineTransformIdentity;
    
    MKCGAxis Y = MKCGAxisY;
    CGFloat y0 = MKCGRectGetMin(f1, Y);//pin视图在listView中的位置
    CGFloat y1 = MKCGPointGetValue(offset, Y);//可见区域的y值
    CGFloat topMarrgin = 0;//pin视图与listview顶部的间隔
    topMarrgin += MKUIEdgeInsetsGetEdge(contentInsets, Y, MKUIEdgeInsetsMin);
    CGFloat dy = y0-y1-topMarrgin;
    CGFloat p = 0;
    if(dy<0){
        m = MKCGAffineTransformMakeTranslation(Y, -dy);
        //
        p = -dy/pinView.bounds.size.height;
        p = MIN(1,MAX(0,p));
    }
    pinView.transform = m;//让自身pin在listView的顶部
    [self setBackgroundColorWithScrollOffsetPercent:p];//修改背景色
    [self onScrollViewDidScroll:listView];
}

#pragma mark - delegate:MKUIListCellViewProtocol,MKUIListSectionViewProtocol
- (void)listView:(MKUIListView *)listView didAddAtIndexPath:(NSIndexPath *)indexPath{
    [self _onDidAddTo:listView];
}
- (void)listView:(MKUIListView *)listView didDeleteAtIndexPath:(nonnull NSIndexPath *)indexPath{
    [self _onDidDeleteFrom:listView];
}
- (void)listView:(MKUIListView *)listView willDisplayAtIndexPath:(nonnull NSIndexPath *)indexPath{
    [self _onWillDisplayTo:listView];
}
- (void)listView:(MKUIListView *)listView didEndDisplayingAtIndexPath:(NSIndexPath *)indexPath{
    [self _onDidEndDisplaying:listView];
}
- (void)listView:(MKUIListView *)listView didAddAtSection:(NSInteger)section kind:(MKUIListViewSectionViewKind)kind{
    [self _onDidAddTo:listView];
}
- (void)listView:(MKUIListView *)listView didDeleteAtSection:(NSInteger)section kind:(MKUIListViewSectionViewKind)kind{
    [self _onDidDeleteFrom:listView];
}
- (void)listView:(MKUIListView *)listView willDisplayAtSection:(NSInteger)section kind:(MKUIListViewSectionViewKind)kind{
    [self _onWillDisplayTo:listView];
}
- (CGFloat)listView:(MKUIListView *)listView zIndexFor:(CGFloat)zIndex atSection:(NSInteger)section kind:(MKUIListViewSectionViewKind)kind{
    return [self _calZIndex:zIndex];
}
- (CGFloat)listView:(MKUIListView *)listView zIndexFor:(CGFloat)zIndex atIndexPath:(NSIndexPath *)indexPath{
    return [self _calZIndex:zIndex];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if([keyPath isEqualToString:NSStringFromSelector(@selector(contentOffset))]){
        [self _onContentOffsetChange];
    }
}
- (void)setBackgroundColorWithScrollOffsetPercent:(CGFloat)p{
    UIColor *c1 = [UIColor.lightGrayColor mk_colorWithAlpha:0];
    UIColor *c2 = [UIColor.lightGrayColor mk_colorWithAlpha:0.5];
    UIColor *c = MKUIColorInterpolate(c1, c2, p);
    self.barContainer.backgroundColor = c;
}
- (void)onScrollViewDidScroll:(UIScrollView *)scrollView{
}
#pragma mark - private
- (CGFloat)_calZIndex:(CGFloat)zIndex{
    return zIndex+1000000;
}
- (void)_onDidAddTo:(MKUIListView *)listView{
    [listView addObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) options:(NSKeyValueObservingOptionNew) context:nil];
}
- (void)_onDidDeleteFrom:(MKUIListView *)listView{
    [listView removeObserver:self forKeyPath:NSStringFromSelector(@selector(contentOffset)) context:nil];
}
- (void)_onWillDisplayTo:(MKUIListView *)listView{
    [self _onContentOffsetChange];
    
}
- (void)_onDidEndDisplaying:(MKUIListView *)listView{
    [self _onContentOffsetChange];
}
- (void)_onContentOffsetChange{
    MKUIListView *listView = [self mk_firstSuperViewWithClass:[MKUIListView class]];
    [self listViewDidChangeContentOffset:listView];
}
- (void)tabBarController:(MKUITabBarController *)controller didSelectIndex:(NSInteger)index{
    [self.mk_listView performBatchUpdates:^{
        [self mk_reloadInListView];
    } animated:YES completion:^(BOOL finished) {
        [self _updateDisplayCells:self.mk_listView];
    }];
}
@end

@interface TestListIndex_TabListBase()<MKUIListViewDelegate>
@property(nonatomic,strong) NSMutableArray<UIView *> *displayViews;
@end
@implementation TestListIndex_TabListBase
- (id)initWithFrame:(CGRect)frame{
    if(self=[super initWithFrame:frame]){
        self.listView = [[MKUIListView alloc] init];
        self.listView.separatorStyle = MKUIListViewCellSeparatorStyleSingleLine;
        self.listView.layer.borderColor = UIColor.lightGrayColor.CGColor;
        self.listView.layer.borderWidth = 1;
        self.listView.sectionInteritemSpacing = 10;
        self.listView.cellInteritemSpacing = 10;
        self.listView.delegate = self;
        [self.contentView addSubview:self.listView];
        //
        self.displayViews = [[NSMutableArray alloc] init];
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
    CGRect bounds = self.bounds;
    self.listView.frame = bounds;
    [self.listView mk_autoBounces];
}
- (CGSize)sizeThatFits:(CGSize)size{
    CGSize s = [self.listView sizeThatFits:CGSizeMake(size.width, 9999)];
    if(!self.fullScroll){
        s.height/=2.0;
    }
    return s;
}
- (void)notifyReloadView{
    TestListIndex_TabCell *tabCell = [self mk_firstSuperViewWithClass:TestListIndex_TabCell.class];
    MKUIListView *outListView = self.mk_listView;
    [outListView performBatchUpdates:^{
        [tabCell mk_reloadInListView];
    } animated:YES completion:^(BOOL finished) {
        [self notifyOutListViewScroll:outListView];
    }];
}
- (void)notifyOutListViewScroll:(MKUIListView *)listView{
    CGRect rect = [self getDisplayRect];
    [self didDisplayRect:rect];
}
- (CGRect)getDisplayRect{
    CGRect rect = self.listView.mk_displayRectInWindow;
    return rect;
}
- (void)didDisplayRect:(CGRect)rect{
    NSArray<UIView *> *views = [self.listView viewsInRect:rect];
    [self _displayViews:views];
}
- (void)_displayViews:(NSArray<UIView *> *)views{
    NSArray *addViews = [views mk_removeObjectsInArray:self.displayViews];
    NSArray *deleteViews = [self.displayViews mk_removeObjectsInArray:views];
    for(UIView *v in addViews){
        if([v conformsToProtocol:@protocol(TestListIndex_TabListCellProtocol)]){
            UIView<TestListIndex_TabListCellProtocol> *cell = (UIView<TestListIndex_TabListCellProtocol> *)v;
            if([cell respondsToSelector:@selector(tabListView:willDisplayAtIndexPath:)]){
                [cell tabListView:self.listView willDisplayAtIndexPath:[self.listView indexPathForCell:cell]];
            }
        }
    }
    for(UIView *v in deleteViews){
        if([v conformsToProtocol:@protocol(TestListIndex_TabListCellProtocol)]){
            UIView<TestListIndex_TabListCellProtocol> *cell = (UIView<TestListIndex_TabListCellProtocol> *)v;
            if([cell respondsToSelector:@selector(tabListView:didEndDisplayingAtIndexPath:)]){
                [cell tabListView:self.listView didEndDisplayingAtIndexPath:[self.listView indexPathForCell:cell]];
            }
        }
    }
    [self.displayViews removeAllObjects];
    [self.displayViews addObjectsFromArray:views];
}
- (void)listView:(MKUIListView *)listView willDisplayCell:(UIView *)v forItemAtIndexPath:(NSIndexPath *)indexPath{
    if([self.displayViews containsObject:v]){
        return;
    }
    CGRect rect = v.mk_displayRectInWindow;
    if(CGRectIsNull(rect)){
        return;
    }
    UIView<TestListIndex_TabListCellProtocol> *cell = (UIView<TestListIndex_TabListCellProtocol> *)v;
    if([cell respondsToSelector:@selector(tabListView:willDisplayAtIndexPath:)]){
        [cell tabListView:self.listView willDisplayAtIndexPath:[self.listView indexPathForCell:cell]];
    }
    if(v)[self.displayViews addObject:v];
}
- (void)listView:(MKUIListView *)listView didEndDisplayingCell:(UIView *)v forItemAtIndexPath:(NSIndexPath *)indexPath{
    if(![self.displayViews containsObject:v]){
        return;
    }
    UIView<TestListIndex_TabListCellProtocol> *cell = (UIView<TestListIndex_TabListCellProtocol> *)v;
    if([cell respondsToSelector:@selector(tabListView:didEndDisplayingAtIndexPath:)]){
        [cell tabListView:self.listView didEndDisplayingAtIndexPath:[self.listView indexPathForCell:cell]];
    }
    [self.displayViews removeObject:v];
}
- (void)tabBarContentViewDidDisapper:(BOOL)animated{
    [self _displayViews:nil];
}
@end

@interface TestListIndex_TabList1()
@end
@implementation TestListIndex_TabList1
- (id)initWithName:(NSString *)name{
    if(self=[self init]){
        self.name = name;
        self.tabBarItem.title = self.name;
        [self reloadData];
    }
    return self;
}
- (void)reloadData{
    @MK_WEAKIFY(self);
    [self.listView addSection];
    [self.listView addItem:[MKUIElementListViewCellSwitch testSwitchElementWithTitle:@"是否填充整个cell" on:self.fullScroll whenChange:^(BOOL on) {
        @MK_NORMALIZE(self);
        self.fullScroll = on;
        [self notifyReloadView];
    }]];
    //
    TestListIndex_AutuRefreshSM *autoSM = [[TestListIndex_AutuRefreshSM alloc] initWithName:self.name];
    autoSM.whenChange = ^(TestListIndex_AutuRefreshSM * _Nonnull sm) {
        @MK_NORMALIZE(self);
        [self notifyReloadView];
    };
    [self.listView addSectionModel:autoSM];
}
- (void)dealloc{
    
}
@end


@interface TestListIndexViewController ()
@property(nonatomic,strong) TestListIndex_HeadView *headView;
@property(nonatomic,strong) MKUIFillingLayoutConstraint *flowlayout;
@end

@implementation TestListIndexViewController
+ (MKTFuncItem *)funcItem{
    return [MKTFuncItem funcWithName:@"复杂ListView首页" viewControllerClass:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.headView = [[TestListIndex_HeadView alloc] init];
    [self.view addSubview:self.headView];
    //
    self.flowlayout = [[MKUIFillingLayoutConstraint alloc] initWithItems:@[self.headView,self.listView] fillingItem:self.listView constraintParam:(MKUIFillingLayoutConstraint_V_C) contentInsets:UIEdgeInsetsZero interitemSpacing:0];
    //
    self.listView.style = MKUIListViewStylePlain;
    self.listView.plainStyleUseGroupInsets = YES;
    self.listView.sectionInteritemSpacing = 10;
    [self _reloadListView];
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    CGRect bounds = self.safeBounds;
    CGRect f1 = bounds;
    f1.size.height = [self.headView sizeThatFits:bounds.size].height;
    self.headView.frame = f1;
    //
    self.listView.frame = bounds;
    self.listView.contentInset = UIEdgeInsetsMake(f1.size.height, 0, 0, 0);
//    self.flowlayout.bounds = bounds;
//    [self.flowlayout layoutItemsWithResizeItems:YES];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    NSArray<UIView *> *views = self.listView.visibleCells;
    for(UIView *v in views){
        if([v conformsToProtocol:@protocol(MKUIListCellViewProtocol)]){
            UIView<MKUIListCellViewProtocol> *cell = (UIView<MKUIListCellViewProtocol> *)v;
            if([cell respondsToSelector:@selector(listView:willDisplayAtIndexPath:)]){
                [cell listView:self.listView willDisplayAtIndexPath:[self.listView indexPathForCell:cell]];
            }
        }
    }
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    NSArray<UIView *> *views = self.listView.visibleCells;
    for(UIView *v in views){
        if([v conformsToProtocol:@protocol(MKUIListCellViewProtocol)]){
            UIView<MKUIListCellViewProtocol> *cell = (UIView<MKUIListCellViewProtocol> *)v;
            if([cell respondsToSelector:@selector(listView:didEndDisplayingAtIndexPath:)]){
                [cell listView:self.listView didEndDisplayingAtIndexPath:[self.listView indexPathForCell:cell]];
            }
        }
    }
}
- (void)_reloadListView{
    [self.listView deleteAllSections];
    //
    [self.listView addSection];
    @MK_WEAKIFY(self);
    [self.listView addItem:[MKUIElementListViewCellSwitch testSwitchElementWithTitle:@"HeadView背景自动透明" on:YES whenChange:^(BOOL on) {
        @MK_NORMALIZE(self);
        if(on){
            self.headView.scrollView = self.listView;
        }else{
            self.headView.scrollView = nil;
        }
    }]];
    [self.listView addItem:[MKUIElementListViewCellButton testButtonElementWithTitle:@"二级页面" buttonStyle:(MKUIElementViewButtonStyleDefault) whenClick:^(MKUIElementListViewCellButton * _Nonnull el) {
        @MK_NORMALIZE(self);
        UIViewController *vc = [[UIViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }]];
    self.headView.scrollView = self.listView;
    //
    [self.listView addSectionModel:[[TestListIndex_AutuRefreshSM alloc] initWithName:@"head"]];
    //
    [self.listView addSection];
    [self.listView addItem:[TestListIndex_TabCell new]];
    //
    [self.listView addSectionModel:[[TestListIndex_AutuRefreshSM alloc] initWithName:@"foot"]];
    //
    [self.listView addSection];
    [self.listView addItem:[MKUIElementListViewCellButton testButtonElementWithTitle:[NSString stringWithFormat:@"刷新"] buttonStyle:(MKUIElementViewButtonStyleDefault) whenClick:^(MKUIElementListViewCellButton * _Nonnull el) {
        @MK_NORMALIZE(self);
        [self.listView reloadData];
    }]];
}

@end

@implementation TestListIndex_AutuRefreshSM
- (id)initWithName:(NSString *)name{
    if(self=[self init]){
        self.name = name;
    }
    return self;
}
- (void)didMoveToListView{
    [super didMoveToListView];
    if(self.listView){
        [self initCells];
    }
}
- (void)initCells{
    @MK_WEAKIFY(self);
    for(int i=0;i<10;i++){
        [self addItem:[TestListIndex_CellButton testButtonElementWithTitle:[NSString stringWithFormat:@"%@_按钮_%@",self.name,@(i)] buttonStyle:(MKUIElementViewButtonStyleDefault) whenClick:^(MKUIElementListViewCellButton * _Nonnull el) {
            @MK_NORMALIZE(self);
            [el.mk_listView performBatchUpdates:^{
                [el.mk_listView deleteView:el withAnimation:(MKUIListViewItemAnimationAutomatic)];
            } animated:YES completion:^(BOOL finished) {
                [self _notifyChange];
            }];
        }] withAnimation:(MKUIListViewItemAnimationAutomatic)];
    }
    [self setSectionView:[MKUIElementListViewCellSwitch testSwitchElementWithTitle:[NSString stringWithFormat:@"定时刷新本分组:%@",self.name] on:NO whenChange:^(BOOL on) {
        @MK_NORMALIZE(self);
        if(on){
            @MK_WEAKIFY(self);
            __block NSInteger count = 0;
            __block BOOL addFlag = YES;
            self.autoRefrehSMTimer = [NSTimer mk_scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
                @MK_NORMALIZE(self);
                count++;
                if(count%40==0){
                    addFlag = !addFlag;
                }
                [self.listView performBatchUpdates:^{
                    if(addFlag){
                        @MK_WEAKIFY(self);
                        [self addItem:[TestListIndex_CellButton testButtonElementWithTitle:[NSString stringWithFormat:@"%@_按钮_%@",self.name,@(count)] buttonStyle:(MKUIElementViewButtonStyleDefault) whenClick:^(MKUIElementListViewCellButton * _Nonnull el) {
                            @MK_NORMALIZE(self);
                            [el.mk_listView performBatchUpdates:^{
                                [el.mk_listView deleteView:el withAnimation:(MKUIListViewItemAnimationAutomatic)];
                            } animated:YES completion:^(BOOL finished) {
                                [self _notifyChange];
                            }];
                        }] withAnimation:(MKUIListViewItemAnimationAutomatic)];
                    }else{
                        [self deleteItemAtIndex:self.numberOfItems-1 withAnimation:(MKUIListViewItemAnimationAutomatic)];
                    }
                } animated:YES completion:^(BOOL finished) {
                    [self _notifyChange];
                }];
            }];
            [[NSRunLoop currentRunLoop] addTimer:self.autoRefrehSMTimer forMode:NSRunLoopCommonModes];
        }else{
            [self.autoRefrehSMTimer invalidate];
            [self _notifyChange];
        }
    }] kind:(MKUIListViewSectionViewKindOfFoot)];
    
    [self setSectionView:[TestFunButton buttonWithTitle:@"清空" click:^(TestFunButton * _Nonnull button) {
        @MK_NORMALIZE(self);
        [self.listView performBatchUpdates:^{
            [self deleteViews:self.cellsForItems withAnimation:(MKUIListViewItemAnimationAutomatic)];
        } animated:YES completion:^(BOOL finished) {
            [self _notifyChange];
        }];
    }] kind:(MKUIListViewSectionViewKindOfHead)];
}
- (void)dealloc{
    [self.autoRefrehSMTimer invalidate];
}
- (void)_notifyChange{
    if(self.whenChange){
        self.whenChange(self);
    }
}
@end

@implementation TestListIndex_CellButton
- (void)tabListView:(MKUIListView *)listView willDisplayAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"willDisplayAtIndexPath:%@,%@",indexPath,self.elementView.titleText);
}
- (void)tabListView:(MKUIListView *)listView didEndDisplayingAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"didEndDisplayingAtIndexPath:%@,%@",indexPath,self.elementView.titleText);
}
@end
